<?php

require_once APPLICATION_PATH . '\models\Users.php';
require_once APPLICATION_PATH . '\models\Home.php';
require_once APPLICATION_PATH . '\models\PublishSubscribe.php';


/**
 * This controller deals with all actions on the user account (registration, 
 * login, logout, password forgotten, and view of the public profile page).
 */
class UserController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    
    public function indexAction() {
        // action body
       header("Location: index/home");
    }

    /**
     * Registration action
     * @author Matej Kollar
     */
    public function registrationAction() {
        // action body

        // Set page's title
        $this->view->headTitle("What's Up :: Registration");
        
        // Add client side form validation
        $this->view->headScript()->appendFile('/WhatsUpProject/public/js/formValidation.js');

        // Add the formular to the view
        $form = new Application_Form_Registration();
        $form->setAction($this->view->url());
        $this->view->form = $form;       

        if ($this->getRequest()->getParam("confirmationCode")) {
            $cC = $this->getRequest()->getParam("confirmationCode");
            Model_Users::unlock($cC);
            $this->view->registrationStatus = "confirmated";
        }

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $cC = Model_Users::insert($form->getValues());
                Model_Users::sendConfirmationMail($_POST["email"], $cC);
                $this->view->registrationStatus = "mailed";
            }
        }
    }

    /**
     * Login action
     * @author Matej Kollar
     */
    public function loginAction() {
        // action body

        // Set page's title
        $this->view->headTitle("What's Up :: Log In");
        
        // Add client side form validation
        $this->view->headScript()->appendFile('/WhatsUpProject/public/js/formValidation.js');

        // Add the formular to the view
        $form = new Application_Form_Login();
        $form->setAction($this->view->url());
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $successful = Model_Users::createSession($_POST["email"], $_POST["password"]);
                if ($successful) {
                    $this->view->loginStatus = "successful";
                    $this->view->headScript()->appendFile('/WhatsUpProject/public/js/redirection.js');
                    header("Refresh:5; URL=../");
                } else {
                    $this->view->loginStatus = "failed";
                }
            }
        }
    }

    /**
     * Logout action
     * @author Matej Kollar
     */
    public function logoutAction() {
        // action body
        
        // Set page's title
        $this->view->headTitle("What's Up :: Log Out");
        
        Model_Users::destroySession();
        $this->view->headScript()->appendFile('/WhatsUpProject/public/js/redirection.js');
        header("Refresh:5; URL=../");
    }

    /**
     * Forgot password
     * @author Matej Kollar
     */
    public function forgotAction() {
        // action body
        
        // Set page's title
        $this->view->headTitle("What's Up :: Forgot your password?");
        
        // Add client side form validation
        $this->view->headScript()->appendFile('/WhatsUpProject/public/js/formValidation.js');

        // Add the formular to the view
        $form = new Application_Form_Forgot();
        $form->setAction($this->view->url());
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                $successful = Model_Users::sendPasswordMail($_POST["email"]);
                if ($successful) {
                    $this->view->forgotStatus = "successful";
                } else {
                    $this->view->forgotStatus = "failed";
                }
            }
        }
    }

    /**
     * Public page/profile of the current user.
     * @author Christophe Sourisse
     */
    public function profileAction() {
        // Get the session from the registry
        $session = Zend_Registry::get("my_session_namespace");

        // Pass data about logged user to the view
        $this->view->topic = $session->user;
        $this->view->postsFromTopics = Model_Home::getNewMessages_sorted($session->user["topics"]);
        $this->view->postsFromCurrentUser = Model_Home::getUserPosts_sorted($session->user["id"]);
        $this->view->topics = Model_Users::getUsers($session->user["topics"]);
        $this->view->subscribers = Model_PublishSubscribe::getSubscribers($session->user["id"]);
    }
    
    /**
     * Update action: Uses the input from the update form
     * to change the user's profile data.
     * @author Dominik Imsirovic
     */
    public function updateAction(){
        
         // Set page's title
        $this->view->headTitle("What's Up :: Edit your profile");
        
        //get the session
          $session = Zend_Registry::get("my_session_namespace");
        
        // Add the formular to the view
        $form = new Application_Form_Update();
        $form->setAction($this->view->url());
        $this->view->form = $form;
        
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
               
               if(!$form->picture->receive()){
                    echo "Couldn't upload picture!";
                }
                $location = $form->picture->getValue();
                
              //  echo "<img src=\"..\images\upload/".$location."\" alt=\"".picture."\" /> <br/>";
                 
                //Prevent SQL injection
                    $_POST["name"]=Model_Users::preventMySqlInjection($_POST["name"]);
                    $_POST["location"]=Model_Users::preventMySqlInjection($_POST["location"]);
                    $_POST["birthdate"]=Model_Users::preventMySqlInjection($_POST["birthdate"]);
                    $_POST["description"]=Model_Users::preventMySqlInjection($_POST["description"]);
                    $_POST["picture"]=Model_Users::preventMySqlInjection($_POST["picture"]);
                
                    
                    /*If the uploaded picture doesn't
                     * belong to the correct datatype
                     * then the profile picture won't be updated.
                    */
                    if(!Model_Users::endsWith($location,".jpg")&& 
                            !Model_Users::endsWith($location,".jpeg")&&
                        !Model_Users::endsWith($location,".gif")&&
                         !Model_Users::endsWith($location,".png") ){
                        $pictureString="";
                    }else{
                        $pictureString=",picture='".$location."' ";
                    }
                    
                
                    //Update database
                $db = Zend_Registry::get("my_db");
                 $stmt = $db->query("UPDATE users SET name = '".$_POST["name"]."' , 
                                       location = '".$_POST["location"]."', 
                                       birthdate = '".$_POST["birthdate"]."',
                                       description = '".$_POST["description"]."'"
                                     .$pictureString."WHERE id = '".$session->user["id"]."'"); 
                 
                 //Also update current session object
                 $session->user["name"]=$_POST["name"];
                 $session->user["location"]=$_POST["location"];
                 $session->user["birthdate"]=$_POST["birthdate"];
                 $session->user["description"]=$_POST["description"];
                 
                 if(strcmp($pictureString,"")!=0)
                 $session->user["picture"]= $location;
                                 
                    $stmt->execute(); 
                     header('Location: ../search/user');
            }
        } 
    }
    
    /**
     * Topic action 
     * @author Dominik Imsirovic
     */
    public function topicAction(){
        
        // Set page's title
        $this->view->headTitle("What's Up :: Create a new topic");
        
        //Get session object
        $session = Zend_Registry::get("my_session_namespace");
        
        // Add the formular to the view
        $form = new Application_Form_Topic();
        $form->setAction($this->view->url());
        $this->view->form = $form;
        
        /*Post an error message if there already exists a 
        topic with the given name*/
        if(isset($_GET["error"]))
                $error="This topic name is not available anymore. 
                       Please enter a different one.";
        else $error="";
        
        //Pass error message to view
        $this->view->error=$error;
        
        
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($_POST)) {
                
                /*If there is already a topic with the given name then don't 
                insert it into the database*/
                $topic=Model_Users::getUserBySurname($_POST["topicName"]);
               if(!isset($topic["userName"])){
               Model_Users::insertTopic($_POST);
               header('Location: ../search/user?avatar='.$_POST["topicName"]);
               }
               else{
                   header('Location: topic?error=true');
               }
            }
        } 
        
        
        
    }

}
